package com.example.a2212park

import android.content.Intent
import android.content.res.Resources
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.a2212park.databinding.ActivitySplashBinding
import com.example.common.view.view.BaseMvvmActivity
import com.example.main.MainActivity
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.roundToInt

@AndroidEntryPoint
//首页倒计时页面
class SplashActivity : BaseMvvmActivity<ActivitySplashBinding>() {
    override fun getLayoutId(): Int = R.layout.activity_splash
    override fun initView() {
        // 初始化进度条
        mDataBinding.cp.max = 100
        mDataBinding.cp.progress = 0

        var hasNavigated = false

        // 启动倒计时和进度动画
        lifecycleScope.launch {
            val totalSeconds = 5
            val totalMilliseconds = totalSeconds * 1000L
            var elapsedMilliseconds = 0L

            // 更新频率为50ms以实现更精确的进度控制
            while (elapsedMilliseconds <= totalMilliseconds && !hasNavigated) {
                // 计算精确的进度百分比（从0%到100%）
                val progress = (elapsedMilliseconds.toDouble() / totalMilliseconds.toDouble()) * 100

                // 保留两位小数并更新进度条
                val roundedProgress = (progress * 100).roundToInt() / 100f
                mDataBinding.cp.setProgressCompat(roundedProgress.toInt(), true)

                // 计算显示的倒计时秒数
                val remainingSeconds = ((totalMilliseconds - elapsedMilliseconds) / 1000.0).toInt()
                mDataBinding.btnCode.text = "${remainingSeconds}s"

                // 检查是否倒计时结束
                if (elapsedMilliseconds >= totalMilliseconds && !hasNavigated) {
                    hasNavigated = true
                    startActivity(
                        Intent(
                            this@SplashActivity,
                            MainActivity::class.java
                        )
                    )
                    finish()
                }

                delay(50) // 每50ms更新一次，更流畅的动画效果
                elapsedMilliseconds += 50
            }
        }

        // 点击跳转
        mDataBinding.btnCode.setOnClickListener {
            if (!hasNavigated) {
                hasNavigated = true
                startActivity(
                    Intent(
                        this@SplashActivity,
                        MainActivity::class.java
                    )
                )
                finish()
            }
        }

        // 进度条也需要设置点击事件
        mDataBinding.cp.setOnClickListener {
            if (!hasNavigated) {
                hasNavigated = true
                startActivity(Intent(this@SplashActivity, MainActivity::class.java))
                finish()
            }
        }
    }
}
